package org.jeecg.modules.charge.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.entity.charge.ChargeOrderReview;
import org.jeecg.entity.charge.ChargeOrderReviewDetail;
import org.jeecg.modules.charge.service.IChargeOrderReviewDetailService;
import org.jeecg.modules.charge.service.IChargeOrderReviewService;
import org.jeecg.modules.system.entity.WxCarPayConfig;
import org.jeecg.modules.system.service.IWxCarPayConfigService;
import org.jeecg.modules.system.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 定时任务接口
 *
 * @author: Shaopeng
 * @date： 日期：2020年10月24日
 */
@Slf4j
@Api(tags = "收费管理定时任务接口")
@RestController
@RequestMapping(value = "/b/charge/quartz")
public class ChargeQuartzController {

    @Value("${shfft.url}")
    private String shfftUrl;

    @Autowired
    private IWxCarPayConfigService wxCarPayConfigService;

    @Autowired
    private IChargeOrderReviewService chargeOrderReviewService;

    @Autowired
    private IChargeOrderReviewDetailService chargeOrderReviewDetailService;


    @ApiOperation("定时获取交易记录数据")
    @Async("/asyncExecutor")
    @PostMapping(value = "/queryTransList")
    public void queryTransList(){
        //获取orgno 暂时只对应一个
        WxCarPayConfig wxCarPayConfig =  wxCarPayConfigService.getById("199");
        if (wxCarPayConfig == null){
            log.error("获取orgNo失败，无法获取交易记录");
            return;
        }
        //查询订单状态数据 02 支付完成   05退款完成
        String arr[] = {"02","05"};
        for (String status : arr){
            query(status, wxCarPayConfig);
        }
    }

    /**
     * 获取订单信息
     * @param status 02 支付完成   05退款完成
     */
    public void query(String status, WxCarPayConfig wxCarPayConfig){
        long startTime = System.currentTimeMillis();
        Map<String,String> map = new HashMap<>();
        //需要在一天快结束时同步
        map.put("startTime",DateUtils.date2Str(DateUtils.getStartTime(), DateUtils.yyyyMMdd));
        map.put("endTime",DateUtils.date2Str(DateUtils.getEndTime(), DateUtils.yyyyMMdd));
        /*map.put("startTime","20201103");
        map.put("endTime","20201103");*/
        map.put("orgNo",wxCarPayConfig.getOrgNo());
        map.put("status",status);
        log.info(DateUtils.now()+"开始同步交易记录数据");
        log.info("同步参数startTime：{}，endTime：{}，orgNo：{}， status：{}", DateUtils.date2Str(DateUtils.getStartTime(), DateUtils.yyyyMMdd),
                DateUtils.date2Str(DateUtils.getEndTime(), DateUtils.yyyyMMdd), wxCarPayConfig.getOrgNo(), status);
        String jsonString = JSONObject.toJSONString(map);
        try {
            JSONObject  jsonObject = RestTemplateUtil.doPost(shfftUrl + "/ori/queryTransList",jsonString);
            log.info("获取交易记录数据返回：{}", jsonObject);
            if ("0000".equals(jsonObject.getString("returnCode"))){
                List<ChargeOrderReview> orderReviews = JSONObject.parseArray(jsonObject.getString("data") , ChargeOrderReview.class);
                if (orderReviews != null && orderReviews.size() > 0){
                    String uuid = "";
                    //订单记录主表数据
                    List<ChargeOrderReview> orderList = new ArrayList<>();
                    //订单记录明细表数据
                    List<ChargeOrderReviewDetail> detailList = new ArrayList<>();
                    //获取主表数据
                    for (ChargeOrderReview chargeOrderReview: orderReviews){
                        //主表id和子表外键相同
                        uuid = UUIDGenerator.getUUID();
                        chargeOrderReview.setId(uuid);
                        chargeOrderReview.setTenantId(wxCarPayConfig.getTenantId());
                        chargeOrderReview.setProjectId(wxCarPayConfig.getProjectId());
                        orderList.add(chargeOrderReview);
                        //获取明细数据
                        if (chargeOrderReview.getOrderDetails().size() > 0){
                            for (ChargeOrderReviewDetail detail : chargeOrderReview.getOrderDetails()){
                                detail.setOrderId(uuid);
                                detail.setTenantId(wxCarPayConfig.getTenantId());
                                detail.setProjectId(wxCarPayConfig.getProjectId());
                                detail.setOriTransNo(chargeOrderReview.getOriTransNo());
                                detailList.add(detail);
                            }
                        }
                    }
                    chargeOrderReviewService.batchSaveOrUpdate(orderList);
                    chargeOrderReviewDetailService.batchSaveOrUpdate(detailList);
                    log.info("获取交易订单状态为：{}成功新增交易记录：{}条。新增明细记录：{}条,",status, orderList.size(), detailList.size());
                }
            }else {
                log.warn("获取交易记录数据返回失败，原因：{}", jsonObject.getString("resultMsg"));
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
            log.error("定时获取交易记录数据异常！");
        }finally {
            log.info("定时获取交易记录数据完成，共耗时"+(System.currentTimeMillis()-startTime));
        }
    }

}
